#include "sdlqtrgb.h"
#include <SDL.h>
#include <QMessageBox>
#include <fstream>
#include <QDir>
#pragma comment(lib, "SDL2.lib")
static SDL_Window *sdl_win = NULL;
static SDL_Renderer *sdl_render = NULL;
static SDL_Texture *sdl_texture = NULL;
static int sdl_width = 0;
static int sdl_height = 0;
static unsigned char *yuv = NULL;
static int pix_size = 2;
static std::ifstream yuv_file;
void SdlQtRGB::timerEvent(QTimerEvent *ev)
{
    yuv_file.read((char *)yuv, sdl_width * sdl_height * 1.5);
    if (yuv_file.bad())
    {
        if (!yuv_file.eof())
        {
            QMessageBox::warning(this, "??", "??????");
        }
        return;
    }
    SDL_UpdateTexture(sdl_texture, NULL, yuv,
                      sdl_width // ?? y????
    );
    SDL_RenderClear(sdl_render);
    SDL_Rect rect;
    rect.x = 0;
    rect.y = 0;
    rect.w = sdl_width * ui.label->devicePixelRatio();
    rect.h = sdl_height * ui.label->devicePixelRatio();
    SDL_RenderCopy(sdl_render, sdl_texture, &rect, &rect);
    SDL_RenderPresent(sdl_render);
}

SdlQtRGB::SdlQtRGB(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    auto s = qApp->applicationDirPath();
    s += "/400_300_25.yuv";
    s = QDir::toNativeSeparators(s);
    yuv_file.open(s.toStdString(), std::ios::binary);
    if (!yuv_file.is_open())
    {
        QMessageBox::warning(this, "??", "??????");
        return;
    }
    sdl_width = 400;
    sdl_height = 300;
    ui.label->resize(sdl_width, sdl_height);
    // ???SDL
    SDL_Init(SDL_INIT_VIDEO);
    // ????
    sdl_win = SDL_CreateWindowFrom((void *)ui.label->winId());
    // ?????
    sdl_render = SDL_CreateRenderer(sdl_win, -1, SDL_RENDERER_ACCELERATED);

    sdl_texture = SDL_CreateTexture(sdl_render,
                                    SDL_PIXELFORMAT_IYUV,
                                    SDL_TEXTUREACCESS_STREAMING,
                                    sdl_width,
                                    sdl_height);
    yuv = new unsigned char[sdl_width * sdl_height * pix_size];
    memset(yuv, 0, sdl_width * sdl_height * pix_size);
    startTimer(10);
}
